import 'package:mobx/mobx.dart';
import '../models/share_post_model.dart';
import '../services/share_service.dart';
import '../services/user_service.dart';
import 'auth_store.dart';

part 'share_store.g.dart';

class ShareStore = _ShareStore with _$ShareStore;

abstract class _ShareStore with Store {
  final ShareService _shareService = ShareService();
  final UserService _userService = UserService();
  final AuthStore _authStore;

  _ShareStore(this._authStore);

  @observable
  ObservableList<SharePostModel> shares = ObservableList<SharePostModel>();

  @observable
  SharePostModel? currentShare;

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @computed
  List<SharePostModel> get collectedShares {
    return shares.where((share) => share.isCollected).toList();
  }

  @computed
  List<SharePostModel> get userShares {
    if (_authStore.currentUser == null) return [];
    return shares
        .where((share) => share.userId == _authStore.currentUser!.id)
        .toList();
  }

  @action
  Future<void> loadShares() async {
    isLoading = true;
    errorMessage = null;

    try {
      final allShares = _shareService.getAllShares();
      shares.clear();
      shares.addAll(allShares);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load shares failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> createSampleShares() async {
    isLoading = true;
    errorMessage = null;

    try {
      await _shareService.addSampleShares();
      await loadShares();
      isLoading = false;
    } catch (e) {
      errorMessage = 'Add sample shares failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<SharePostModel?> createShare(
    String description,
    List<String> imageUrls,
  ) async {
    if (_authStore.currentUser == null) return null;

    isLoading = true;
    errorMessage = null;

    try {
      final share = await _shareService.createSharePost(
        userId: _authStore.currentUser!.id,
        description: description,
        imageUrls: imageUrls,
      );

      shares.insert(0, share); // 添加到列表开头
      isLoading = false;
      return share;
    } catch (e) {
      errorMessage = 'Create share failed: ${e.toString()}';
      isLoading = false;
      return null;
    }
  }

  @action
  Future<void> toggleShareCollected(String shareId) async {
    if (_authStore.currentUser == null) return;

    try {
      final shareIndex = shares.indexWhere((s) => s.id == shareId);
      if (shareIndex >= 0) {
        final share = shares[shareIndex];
        final newState = !share.isCollected;

        await _shareService.toggleCollected(shareId, newState);

        // 更新本地状态
        shares[shareIndex] = _shareService.getShareById(shareId)!;

        // 如果当前分享是被修改的分享，也更新它
        if (currentShare?.id == shareId) {
          currentShare = _shareService.getShareById(shareId);
        }
      }
    } catch (e) {
      errorMessage = 'Update share collection status failed: ${e.toString()}';
    }
  }

  @action
  Future<void> deleteShare(String shareId) async {
    isLoading = true;
    errorMessage = null;

    try {
      await _shareService.deleteSharePost(shareId);
      shares.removeWhere((s) => s.id == shareId);
      if (currentShare?.id == shareId) {
        currentShare = null;
      }
      isLoading = false;
    } catch (e) {
      errorMessage = 'Delete share failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  void selectShare(String shareId) {
    currentShare = _shareService.getShareById(shareId);
  }

  @action
  Future<void> viewShare(String shareId) async {
    if (_authStore.currentUser == null) return;

    try {
      await _shareService.addViewer(shareId, _authStore.currentUser!.id);

      // 更新本地状态
      final shareIndex = shares.indexWhere((s) => s.id == shareId);
      if (shareIndex >= 0) {
        shares[shareIndex] = _shareService.getShareById(shareId)!;
      }

      if (currentShare?.id == shareId) {
        currentShare = _shareService.getShareById(shareId);
      }
    } catch (e) {
      errorMessage = 'Update view record failed: ${e.toString()}';
    }
  }

  @action
  Future<List<SharePostModel>> searchShares(String query) async {
    isLoading = true;
    errorMessage = null;

    try {
      final results = _shareService.searchShares(query);
      isLoading = false;
      return results;
    } catch (e) {
      errorMessage = 'Search shares failed: ${e.toString()}';
      isLoading = false;
      return [];
    }
  }

  @action
  Future<List<SharePostModel>> getUserSharePosts(String userId) async {
    isLoading = true;
    errorMessage = null;

    try {
      final userShares = _shareService.getUserShares(userId);
      isLoading = false;
      return userShares;
    } catch (e) {
      errorMessage = 'Get user shares failed: ${e.toString()}';
      isLoading = false;
      return [];
    }
  }
}
